/*
 * Copyright 2017 hv0912
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.vimhe.ezimp2.handler.validator;

import com.vimhe.ezimp2.config.bean.ColumnConfig;
import com.vimhe.ezimp2.config.bean.ValidatorConfig;
import com.vimhe.ezimp2.config.exception.ConfigException;
import com.vimhe.ezimp2.handler.Validator;
import com.vimhe.ezimp2.handler.bean.CellData;
import com.vimhe.ezimp2.util.ConvertUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import static com.vimhe.ezimp2.Constants.CLASS_TYPE_STRING;

/**
 * 抽象数据验证器
 *
 * @author Vimhe
 */
public abstract class AbstractValidator<T> implements Validator {

    private Class<T> cellValueType;

    @SuppressWarnings("unchecked")
    public AbstractValidator() {
        Type t = this.getClass().getGenericSuperclass();
        cellValueType = (Class<T>) ((ParameterizedType) t).getActualTypeArguments()[0];
    }

    @Override
    @SuppressWarnings("unchecked")
    public final ErrorMessage validate(CellData cellData, ColumnConfig columnConfig) {
        ValidatorConfig validatorConfig = columnConfig.getValidatorConfigMap().get(name());

        // 记录原始数据，用于在错误消息中显示
        Object cellValue = cellData.getValue();

        if (!this.validateType(cellData, columnConfig)) {
            cellData.setValue(cellValue);
            return new ErrorMessage(cellData).setErrorMessage(validatorConfig.getMessage());
        }

        if (!this.validateValue((T) cellData.getValue(), validatorConfig.getValue())) {
            cellData.setValue(cellValue);
            return new ErrorMessage(cellData).setErrorMessage(validatorConfig.getMessage());
        }

        return null;
    }

    /**
     * 数据类型验证，验证成功后会将数据转换为对应的类型
     *
     * @param cellData     单元格数据对象
     * @param columnConfig 单元格配置对象
     * @return 验证通过返回“true”，否则返回“false”
     */
    private boolean validateType(CellData cellData, ColumnConfig columnConfig) {
        if (CLASS_TYPE_STRING.equals(columnConfig.getType())) {
            return true;
        }

        try {
            T cellValue = ConvertUtils.convert(cellData.getValue().toString(), cellValueType);
            cellData.setValue(cellValue);
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    /**
     * 把验证器配置参数转换为指定的数据类型
     *
     * @param configValue 验证器配置参数
     * @param clazz       指定的数据类型
     * @param <V>         对应数据类型的对象
     * @return 指定类型的对象
     */
    protected final <V> V toExpectType(final String configValue, Class<V> clazz) {
        try {
            return ConvertUtils.convert(configValue, clazz);
        } catch (Exception e) {
            throw new ConfigException("配置项【validator > value】的值无法转换为目标类型", e);
        }
    }

    /**
     * 数据逻辑验证
     *
     * @param cellValue   单元格数据
     * @param configValue 验证器值
     * @return 验证通过返回“true”，否则返回“false”
     */
    protected abstract boolean validateValue(final T cellValue, final String configValue);

}
